<?php
/**
 * Created by JetBrains PhpStorm.
 * User: AndreyG
 * Date: 26.01.12
 * Time: 13:17
 * To change this template use File | Settings | File Templates.
 */
class My_Model extends TinyMVC_Model
{

    protected $_data = array();

    protected $_table;

    public function __construct()
    {
        parent::__construct();
        $this->_data['entity'] = array();
        //TODO
        //$this->db->query('SET NAMES UTF8');
        $this->_init();
    }

    public function getData($field)
    {
        return $this->_data['entity'][$field];
    }

    public function setData(array $data)
    {
        foreach($data as $key => $value) {
            $this->_data['entity'][$key] = $value;
        }
    }

    public function getId()
    {
        if(array_key_exists('id', $this->_data['entity'])) {
            return $this->_data['entity']['id'];
        }
        return;
    }

    /*
     * Init table Name
     */
    protected function _init()
    {

    }

    public function save()
    {
        if($this->getId()) {
            $this->db->update($this->_table, $this->_data['entity']);
        } else {
            $this->db->insert($this->_table, $this->_data['entity']);
            $this->setData(array('id' => $this->db->last_insert_id()));
        }
    }

    public function load($id)
    {

    }

    /*
     * Set variables
     * Example: setLocation(1) -- getLocation(),
     * setCategory(array(1,2)) -- getCategory()
     * @param string
     * @param string
     * return mixed
     */
    public function __call($func, $arg)
    {
        if(is_array($arg)) {
            $var = array_shift($arg);
        }

        $method = substr($func,0, 3);

        if($method == 'set') {
           $this->_data[strtolower(substr($func,3))] = $var;
        } elseif($method == 'get') {
           return $this->_data[strtolower(substr($func,3))];
        } else {
            throw new ErrorException("Method not found");
        }
    }



}
